<?php

namespace common\logics;

use Yii;
use common\helpers\Url;
use common\helpers\StringHelper;
use common\helpers\ArrayHelper;

/**
 * 分享功能逻辑模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ShareLogic extends \common\base\Model {

    const TYPE_DEFAULT = 'app';
    const TYPE_DYNAMIC = 'dynamic';
    const TYPE_ARTICLE = 'article';

    /**
     * @var integer 用户UID
     */
    public $user_id = 0;

    /**
     * @var string 分享的应用场景
     */
    public $type;

    /**
     * @var string 分享内容的标题
     */
    public $title;

    /**
     * @var string 分享内容的描述
     */
    public $content;

    /**
     * @var string 分享内容的图标
     */
    public $thumb;

    /**
     * @var string 分享内容的链接地址
     */
    public $url = '';

    /**
     * @var string 构建后的分享链接参数
     */
    private $_params = [];

    /**
     * @var string 是否加密分享链接地址
     */
    private $_safe = false;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'type', 'title', 'content', 'thumb', 'url'], 'safe'],
        ];
    }

    /**
     * 获取分享数据中的描述信息，同时格式化截取
     */
    public function getDescription() {
        return StringHelper::truncate($this->content, 50);
    }

    /**
     * 设置分享地址参数信息
     */
    public function setParams($data = null) {
        $params = [];
        if (!empty($data)) {
            $params['data'] = $data;
        }
        $this->_params = $params;
    }

    /**
     * 设置是否加密分享地址，如user_id不为0则默认加密
     */
    public function setSafe($safe = true) {
        $this->_safe = $safe;
    }

    /**
     * 获取分享的地址
     */
    public function getLink() {
        $params = $this->_params;
        $safe = $this->_safe;
        if ($this->user_id) {
            $params['uid'] = $this->user_id;
            $safe = true;
        }
        return Url::share($this->type, $params, $safe);
    }

    /**
     * 获取分享出去的小图图标
     */
    public function getThumbUrl() {
        $image = $this->thumb;
        if (!$image) {
            $image = ArrayHelper::getValue(Yii::$app->params, 'shareData.thumb');
        }
        return Url::attach($image);
    }

    /**
     * 默认分享数据
     */
    public static function base($uid = 0) {
        $defaultParams = ArrayHelper::getValue(Yii::$app->params, 'shareData');
        $model = static::instance();
        $model->type = self::TYPE_DEFAULT;
        $model->user_id = $uid;
        $model->setAttributes($defaultParams);
        return $model->toArray();
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'title' => function() {
                return StringHelper::truncate($this->title, 30);
            },
            'description',
            'thumb' => 'thumbUrl',
            'link',
        ];
    }

}
